package com.gxa.community.admin.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import javax.crypto.*;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import java.util.UUID;


public class JwtUtil {
    /*
    iss: jwt签发者
    sub: jwt所面向的用户 //就是放我们登录的用户名
    aud: 接收jwt的一方
    iat: jwt的签发时间
    exp: jwt的过期时间，这个过期时间必须要大于签发时间 //过期时间也可以放
    nbf: 定义在什么时间之前，该jwt都是不可用的.
    jti: jwt的唯一身份标识，主要用来作为一次性token, 从而回避重放攻击
    */

    //token生效时间
    private static final long EXPIRE_TIME = 60 * 1000 * 60 * 24 * 6;
    private static final Object JWT_SECRET_KEY = "JuRan_bj287-291-token-secret";

    /**
     * 生成签名
     *
     * @param username 用户名
     * @param secret   用户的密码
     * @return 加密的token
     */
    public static String sign(String username, String secret, Integer uId,String uNick) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);

        Algorithm algorithm = Algorithm.HMAC256(secret);
        String jwtId = UUID.randomUUID().toString();
        String token = JWT.create()
                .withJWTId(jwtId)
                .withSubject(username)
                .withClaim("userId", uId)
                .withClaim("loginAct", uNick)
                .withExpiresAt(date)
                .withIssuedAt(new Date())
                .sign(algorithm);

        return encodeToken(token);
    }

    /**
     * 校验token是否正确
     *
     * @param token_ 加密过的密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token_, String username, String secret) {
        String token = decodeToken(token_);
        System.out.println(token);
        try {
            //根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withSubject(username)
//                    .withClaim("username", username)
                    .build();
            //效验token
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getSubject(String token_) {
        String token = decodeToken(token_);
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getSubject();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static Claim getClaim(String token_, String s) {
        String token = decodeToken(token_);
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(s);
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获得tokenId
     *
     * @return uuid
     */
    public static String getTokenId(String token_) {
        String token = decodeToken(token_);
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getId();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获取token过期时间
     *
     * @return 过期时间
     */
    public static Date getExpiresAt(String token_) {
        String token = decodeToken(token_);
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getExpiresAt();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获取token签发时间
     *
     * @return 签发时间
     */
    public static Date getIssuedAt(String token_) {
        String token = decodeToken(token_);
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getIssuedAt();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static String encodePsw(String psw, String salt) {
        return new SimpleHash("MD5", ByteSource.Util.bytes(psw), salt, 1024).toString();
    }

    private static SecretKey getSecretKey(int bits, String secret) {
        KeyGenerator keyGenerator;
        try {
            keyGenerator = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("aes[" + bits + "] not supported", e);
        }
        keyGenerator.init(bits, new SecureRandom(secret.getBytes()));
        return keyGenerator.generateKey();
    }

    /**
     * 对token二次加密
     *
     * @return 加密后的token
     */
    private static String encodeToken(String token) {
        ByteSource byteSource = null;
        try {
            byteSource = ByteSource.Util.bytes(AESUtils.encryptGCM(token.getBytes(),new SimpleHash("MD5", JWT_SECRET_KEY).getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return byteSource.toHex();
    }

    /**
     * 将密文解密为token
     *
     * @param token_ 加密过的token
     * @return 解密后的token原文
     */
    private static String decodeToken(String token_) {
        ByteSource byteSource = null;
        try {
            byteSource = ByteSource.Util.bytes(AESUtils.decryptGCM(Hex.decode(token_),
                    new SimpleHash("MD5", JWT_SECRET_KEY).getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(byteSource.getBytes());
    }

    public static void main(String[] args) {

        /*decodeToken(encodeToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"));*/
        System.out.println(System.currentTimeMillis());
        System.out.println(JwtUtil.encodePsw("123", "ce1e119a-01f3-41c8-bd46-6c0eaa42bd3f"));
    }
}
